package com.gimi.cloud.bbp.client.service.alipay.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.gimi.cloud.bbp.client.service.alipay.AlipayNotifyService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.commonService.alipay.AliPayService;
import com.gimi.cloud.bbp.dao.dao.log.LogAlipayNotifyDao;
import com.gimi.cloud.bbp.entity.log.LogAlipayNotifyEntity;

/**
 * 支付宝异步通知
 * @author 李林峰
 * @version 1.0
 * @Description
 * @create 2018年2月5日
 */
@Service
public class AlipayNotifyServiceImpl implements AlipayNotifyService{
	@Autowired LogAlipayNotifyDao logAlipayNotifyDao;
	
	private static final Logger log = LoggerFactory.getLogger(AlipayNotifyServiceImpl.class);

	@Autowired AliPayService aliPayService;

	@Override
	public Response alipayNotify(Map<String, String[]> requestParams) {
		log.info("支付宝异步通知参数:"+JSON.toJSONString(requestParams));
		Map<String, String> params = null;
		try {
			params = aliPayService.alipayNotifyValidation(requestParams);
		} catch (AlipayApiException e) {
			log.error("支付宝参数校验异常");
			e.printStackTrace();
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR, "支付宝参数校验异常");
		}
		
		if (params == null) {
			log.error("支付宝参数校验异常");
			throw new MsgException(ResponseCodeEnum.SERVICE_ERROR, "支付宝参数校验异常");
		}
		LogAlipayNotifyEntity record = new LogAlipayNotifyEntity();
		record.setAnNotifyParams(JSON.toJSONString(params));
		logAlipayNotifyDao.baseInsert(record);
		
		//TODO 异步通知参数格式未知，等等测试完成后完成后续代码，完成对订单状态调整
		
		return new Response(ResponseCodeEnum.INVALID);
	}

}